package org.game.handler;

import akka.actor.typed.ActorRef;
import lombok.extern.slf4j.Slf4j;
import org.common.akka.message.BaseMsg;
import org.common.akka.message.ClientUpMsg;
import org.common.akka.message.RoleLoginMsg;
import org.common.dispatcher.CMD;
import org.common.handler.BaseProtoHandler;
import org.common.mongo.MongoService;
import org.common.mongo.collection.SimpleRoleCollection;
import org.common.netty.Pack;
import org.common.utils.SpringUtils;
import org.game.obj.LoginServerContext;
import org.game.obj.RoleManager;
import org.protobuf.InnerServerMsg;
import org.protobuf.ProtoEnumMsg;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class InnerServerProtoHandler extends BaseProtoHandler {

    /**
     * 角色登录
     */
    @CMD(ProtoEnumMsg.CMD.ID.NOTIFY_GAME_ROLE_LOGIN_VALUE)
    public Pack notifyGameRoleLogin(LoginServerContext lc, InnerServerMsg.L2GRoleLogin up) {
        long roleId = up.getRoleId();
        log.info("角色登录, roleId = {}", roleId);
        MongoService mongoService = SpringUtils.getBean(MongoService.class);
        // 创建actor
        SimpleRoleCollection simpleRoleCollection = mongoService.findById(roleId, SimpleRoleCollection.class);
        if (simpleRoleCollection == null) {
            log.error("没有该角色, roleId = {}", roleId);
            return null;
        }
        RoleManager roleManager = SpringUtils.getBean(RoleManager.class);
        ActorRef<BaseMsg> roleActor = roleManager.createRoleActor(simpleRoleCollection, lc.getChannel());
        RoleLoginMsg roleLoginMsg = new RoleLoginMsg();
        roleLoginMsg.setRoleId(roleId);
        roleLoginMsg.setAccountId(simpleRoleCollection.getAccountId());
        roleActor.tell(roleLoginMsg);
        return null;
    }

    /**
     * 角色协议转发
     */
    @CMD(ProtoEnumMsg.CMD.ID.CLIENT_PROTO_DISPATCH_VALUE)
    public Pack clientProtoDispatch(LoginServerContext lc, InnerServerMsg.L2GClientUpMsg up) {
        long roleId = up.getRoleId();
        log.info("角色上行的协议, roleId = {}", roleId);
        // 发送到对应地RoleActor进行处理
        RoleManager roleManager = SpringUtils.getBean(RoleManager.class);
        ActorRef<BaseMsg> roleActor = roleManager.getRoleActor(roleId);
        if (roleActor == null) {
            log.error("角色尚未登陆, roleId = {}", roleId);
            return null;
        }
        ClientUpMsg clientUpMsg = new ClientUpMsg(up.getData().toByteArray());
        roleActor.tell(clientUpMsg);
        return null;
    }


}
